package com.riguz.forks.framework.plugin.system;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.riguz.forks.framework.Framework;
import com.riguz.forks.framework.db.PoolManager;
import com.riguz.forks.framework.plugin.Plugin;
import com.riguz.gags.base.Strings;
import com.riguz.gags.io.Config;

public class DbPlugin implements Plugin{
    private static final Logger logger = LoggerFactory.getLogger(DbPlugin.class);
    
    @Override
    public String getPluginInfo() {
        return "Forks JDBC plugin";
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean init() {
        Map<String, Object> config = Config.use(Framework.FRAMEWORK_SETTINGS);;
        if (config == null)
            throw new RuntimeException("JDBC config not found.Please check your config:" + Framework.FRAMEWORK_SETTINGS);
        
        List<Map<String, String>> jdbcSettings = (List<Map<String, String>>) config.get("jdbc");
        for( Map<String, String> jdbcSetting:jdbcSettings){
            String name = jdbcSetting.get("poolName");
            if(Strings.isNullOrEmpty(name))
                name = PoolManager.DEFAULT_POOL_NAME;
            Properties p = new Properties();
            for(String key:jdbcSetting.keySet())
                p.setProperty(key, jdbcSetting.get(key));
            logger.info("Creating jdbc pool:{}", jdbcSetting);
            Framework.getPoolManager().createPool(name, p);
        }
        return true;
    }

    @Override
    public void destroy() {
        
    }

}
